<?php namespace Cms\Api;

use Hdphp\Api\Api;

class User extends Api
{
	/**
	 * 获取用户
	 * @param  int 		$id   用户id
	 * @param  string 	$field 字段名
	 * @return mixed
	 */
	public function get($id='',$field=null)
	{
		$id = $id?$id:$_SESSION['id'];

		if(empty($id))
		{
			return ;
		}

		static $list = array();

		$key = "u{$id}";

		if (!isset($list[$key]))
		{
			$cache = S('user');
			
			if (isset($cache[$key]))
			{
				$list[$key] = $cache[$key];
			}
			else
			{
				$user = Db::table('user')->where('id',$id)->first();

				if (!$user)
				{
					return ;
				}

				$list[$key] = $user;

				$count = count( $list );
				while ($count-- > C('api.user_cache_limit'))
				{
					array_shift($list);
				}

				S('user',$list);
			}
		}

		return is_null($field)?$list[$key]:$list[$key][$field];
	}

	//登录检测
	public function isLogin()
	{
		return Rbac::isLogin();
	}

	/**
	 * 登录
	 * @return boolean
	 */
	public function login()
	{
		if(Q('post.code','','strtoupper')!==Q('session.code'))
		{
			$this->error ='验证码错误';
			return false;
		}
		if(!Q('post.username'))
		{
			$this->error ='帐号不能为空';
			return false;
		}

		$user = Db::table('user')->where('username',Q('post.username'))->first();

		if(!$user)
		{
			$this->error = '帐号不存在';
			return false;
		}

		if($user['password'] != md5(Q('post.password').$user['code']))
		{
			$this->error = '密码错误';
			return false;
		}

		$_SESSION['id'] = $user['id'];

		$this->updateLogin($user['id']);

		return true;
	}

	/**
	 * 更新登录状态
	 * @return [type] [description]
	 */
	private function updateLogin($id)
	{
		$data['lastip']=Request::ip();
		$data['logintime']=time();

		Db::table('user')->where('id',$id)->update($data);
	}

	/**
	 * 获取头像
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function getIcon($id='')
	{
		$id = $id?$id:$_SESSION['id'];
		$icon = $this->get($id,'icon');

		if (empty($icon))
		{
			return __PUBLIC__ . '/icon/user.png';
		}
		else
		{
			return __ROOT__ . '/' . $user['icon'];
		}
	}
	/**
	 * 通过魔术方法获取字段值
	 * @param  [type] $method [description]
	 * @param  [type] $params [description]
	 * @return [type]         [description]
	 */
	public function __call($method,$params)
	{
		//字段名
		$field = strtolower(substr($method,3));
		array_push($params, $field);
		return call_user_func_array(array($this,'get'), $params);
	}
}